<template>
  <div>
    <a-input-search
      v-model="selectedEmpNames"
      :placeholder="placeholder"
      :disabled="disabled"
      readOnly
      @search="handleSearch"
    >
      <a-button slot="enterButton" :disabled="disabled">选择</a-button>
    </a-input-search>
    <a-modal
      :title="title"
      :width="modalWidth"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-spin :spinning="confirmLoading">
        <!-- 查询区域 -->
        <div class="query-area">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="8" :sm="12">
                <a-form-item label="员工姓名">
                  <a-input placeholder="请输入员工姓名" v-model="queryParam.empName" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <a-form-item label="员工编号">
                  <a-input placeholder="请输入员工编号" v-model="queryParam.empNo" allowClear></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="12">
                <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>

        <!-- 表格区域 -->
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          :rowSelection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
            type: multiple ? 'checkbox' : 'radio',
          }"
          :customRow="customRowClick"
          @change="handleTableChange"
        >
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getAction } from '@/api/manage'

export default {
  name: 'JSelectEmployeeModal',
  props: {
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请选择员工',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    modalWidth: {
      type: Number,
      default: 800,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '选择员工',
    },
    departName: {
      type: String,
      default: '',
      required: false,
    },
  },
  data() {
    return {
      visible: false,
      confirmLoading: false,
      selectedRowKeys: [],
      selectedEmpKeys: [], // 保存选择的员工ID
      selectedEmpNames: '', // 保存选择的员工名称
      selectedEmployees: [], // 保存选择的员工信息
      departId: '', // 部门ID

      // 查询条件
      queryParam: {
        empName: '',
        empNo: '',
        departName: '',
      },

      // 数据源
      dataSource: [],

      // 表格列
      columns: [
        {
          title: '员工编号',
          dataIndex: 'empNo',
          width: '15%',
          align: 'center',
        },
        {
          title: '员工姓名',
          dataIndex: 'empName',
          width: '15%',
          align: 'center',
        },
        {
          title: '所属部门',
          dataIndex: 'departName',
          width: '20%',
          align: 'center',
        },
        {
          title: '手机号码',
          dataIndex: 'phone',
          width: '15%',
          align: 'center',
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '10%',
          align: 'center',
          customRender: (text) => {
            if (text === 1) {
              return '正常'
            } else if (text === 0) {
              return '冻结'
            } else {
              return text
            }
          },
        },
      ],

      // 分页参数
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },

      loading: false,
      url: {
        list: '/sys/employee/list',
      },
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initSelectedEmployee(val)
        } else {
          this.selectedEmpKeys = []
          this.selectedEmpNames = ''
          this.selectedEmployees = []
          this.selectedRowKeys = []
        }
      },
    },
    // departName: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       this.queryParam.departName = val
    //       this.loadData(1)
    //     } else {
    //       this.departId = ''
    //     }
    //   },
    // },
  },
  created() {
    this.searchReset()
  },
  methods: {
    // 自定义行点击事件
    customRowClick(record) {
      return {
        onClick: () => {
          this.handleRowClick(record)
        },
      }
    },

    // 初始化已选择的员工信息
    initSelectedEmployee(selectedIds) {
      if (!selectedIds) return

      this.loading = true
      let params = { ids: selectedIds }

      getAction('/sys/employee/getEmployeesByIds', params)
        .then((res) => {
          if (res.success) {
            this.selectedEmployees = res.result || []
            this.selectedEmpKeys = this.selectedEmployees.map((item) => item.id)
            this.selectedEmpNames = this.selectedEmployees.map((item) => item.empName).join(',')
            this.selectedRowKeys = this.selectedEmpKeys
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 打开选择框
    handleSearch() {
      if (this.disabled) return

      this.visible = true
      this.loadData(1)
    },

    // 加载数据
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }

      const params = this.getQueryParams()

      this.loading = true

      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || []
            this.ipagination.total = res.result.total || 0
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取查询参数
    getQueryParams() {
      const param = Object.assign({}, this.queryParam)

      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize

      // 如果是通过部门名称筛选，添加departName参数
      console.log('this.departName......................', this.departName)
      if (this.departName) {
        param.departName = this.departName
      }

      return param
    },

    // 选择改变
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys

      if (!this.multiple) {
        this.selectedEmployees = selectedRows
      } else {
        // 保持已经选择的和当前页面选择的
        const selectedIds = selectedRows.map((row) => row.id)
        this.selectedEmployees = this.selectedEmployees.filter((item) => {
          return selectedIds.includes(item.id) || !this.dataSource.map((row) => row.id).includes(item.id)
        })

        // 添加当前页面新选择的
        selectedRows.forEach((row) => {
          const exist = this.selectedEmployees.some((item) => item.id === row.id)
          if (!exist) {
            this.selectedEmployees.push(row)
          }
        })
      }
    },

    // 查询按钮
    searchQuery() {
      this.loadData(1)
    },

    // 重置按钮
    searchReset() {
      this.queryParam = {
        empName: '',
        empNo: '',
        departName: '',
      }
      this.loadData(1)
    },

    // 表格分页、排序、筛选变化
    handleTableChange(pagination, filters, sorter) {
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      this.loadData()
    },

    // 处理行点击事件
    handleRowClick(record) {
      // 获取当前行的key
      const rowKey = record.id

      // 根据是否多选处理不同的逻辑
      if (!this.multiple) {
        // 单选模式：直接设置当前行为选中状态
        this.selectedRowKeys = [rowKey]
        this.selectedEmployees = [record]
      } else {
        // 多选模式：切换选中状态
        const index = this.selectedRowKeys.indexOf(rowKey)
        if (index === -1) {
          // 如果未选中，则添加到选中列表
          this.selectedRowKeys.push(rowKey)

          // 检查记录是否已存在于selectedEmployees中
          const exist = this.selectedEmployees.some((item) => item.id === record.id)
          if (!exist) {
            this.selectedEmployees.push(record)
          }
        } else {
          // 如果已选中，则从选中列表移除
          this.selectedRowKeys.splice(index, 1)

          // 从selectedEmployees中移除
          const empIndex = this.selectedEmployees.findIndex((item) => item.id === record.id)
          if (empIndex !== -1) {
            this.selectedEmployees.splice(empIndex, 1)
          }
        }
      }
    },

    // 确定按钮
    handleOk() {
      this.selectedEmpKeys = this.selectedEmployees.map((item) => item.id)
      this.selectedEmpNames = this.selectedEmployees.map((item) => item.empName).join(',')

      this.$emit('input', this.selectedEmpKeys.join(','))
      this.$emit('change', this.selectedEmpKeys.join(','), this.selectedEmployees)

      this.handleCancel()
    },

    // 取消按钮
    handleCancel() {
      this.visible = false
    },
  },
}
</script>

<style scoped>
.query-area {
  margin-bottom: 16px;
}

/* 添加鼠标悬停样式，提升用户体验 */
:deep(.ant-table-tbody > tr) {
  cursor: pointer;
}

:deep(.ant-table-tbody > tr:hover) {
  background-color: #e6f7ff;
}
</style> 